package com.egg.ylt.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.egg.ylt.R;
import com.egg.ylt.Utils.Constants;
import com.egg.ylt.Utils.CustomUtils;
import com.egg.ylt.Utils.StatusBarUtil;
import com.egg.ylt.Utils.StringUtil;
import com.egg.ylt.adapter.ADA_BabyRelation;
import com.egg.ylt.datePicker.CustomDatePicker;
import com.egg.ylt.pojo.MemberBabyEntity;
import com.egg.ylt.pojo.RelationEntity;
import com.egg.ylt.pojo.UpLoadFileEntity;
import com.egg.ylt.presenter.impl.EditBabyPresenterImpl;
import com.egg.ylt.uploadingphoto.UriUtils;
import com.egg.ylt.view.IEditBabyView;
import com.ruffian.library.widget.RImageView;
import com.yonyou.framework.library.adapter.rv.MultiItemTypeAdapter;
import com.yonyou.framework.library.base.BaseActivity;
import com.yonyou.framework.library.bean.ErrorBean;
import com.yonyou.framework.library.common.utils.AppDateUtil;
import com.yonyou.framework.library.common.utils.AppSharedPreferences;
import com.yonyou.framework.library.common.utils.DisplayUtil;
import com.yonyou.framework.library.common.utils.MoneyFormatUtil;
import com.yonyou.framework.library.common.utils.ToastUtil;
import com.yonyou.framework.library.dialog.AlertDialog;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;

public class ACT_EditBabyInfo extends BaseActivity<EditBabyPresenterImpl> implements IEditBabyView {

    public static final int START_FROM_HEALTH = 0;
    public static final int START_FROM_RELATION = 1;
    public static final int START_FROM_SWITCH = 2;

    @BindView(R.id.rl_include_title)
    RelativeLayout mIncludeRlView;
    @BindView(R.id.include_iv_back)
    ImageView includeIvBack;
    @BindView(R.id.include_tv_title)
    TextView includeTvTitle;
    @BindView(R.id.include_tv_right)
    TextView includeTvRight;
    @BindView(R.id.baby_iv_head_photo)
    RImageView babyIvHeadPhoto;
    @BindView(R.id.baby_edit_name)
    EditText babyEditName;
    @BindView(R.id.baby_tv_birthday)
    TextView babyTvBirthday;
    @BindView(R.id.baby_iv_sex)
    ImageView babyIvSex;
    @BindView(R.id.baby_tv_sex)
    TextView babyTvSex;
    @BindView(R.id.baby_btn_scan_code)
    TextView babyBtnScanCode;
    @BindView(R.id.baby_edit_height)
    EditText babyEditHeight;
    @BindView(R.id.baby_edit_weight)
    EditText babyEditWeight;
    @BindView(R.id.target_view_ll)
    LinearLayout llTargetView;
    @BindView(R.id.tv_select_relation)
    TextView tvRelation;

    private AlertDialog mRelativeDialog;
    private ADA_BabyRelation mRelationAdapter;
    private String selectedRelationId;
    private String selectedRelationName;

    // 拍照回传码
    public final static int CAMERA_REQUEST_CODE = 0;
    // 相册选择回传吗
    public final static int GALLERY_REQUEST_CODE = 1;
    //系统剪裁
    private final static int GO_TO_ZOOM = 3;
    //相关系统权限
    private String[] PERMISSIONS_STORAGE = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,
            Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS};

    // 拍照的照片的存储位置
    private String mTempPhotoPath;
    // 照片所在的Uri地址
    //宝宝头像上传地址
    private Uri imageUri;

    //调用照相机返回图片文件
    private Uri imageCropUri;

    private String mGender;//性别 0男  1女
    private int mResource;
    private String imgUri;
    private String mToken;
    private String mUserId;
    private AppSharedPreferences mSp;
    private CustomDatePicker customDatePicker;
    private AlertDialog mOpenCamersDialog;

    private MemberBabyEntity.ListBean entity;
    private String babyId = "";

    @Override
    protected void getBundleExtras(Bundle extras) {
        entity = (MemberBabyEntity.ListBean) extras.getSerializable("bean");
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.act_edit_baby_info;
    }

    @Override
    protected View getLoadingTargetView() {
        return llTargetView;
    }

    @Override
    protected void initViewsAndEvents() {

        StatusBarUtil.setStatusBarColor(this, R.color.ylt_style_orange);
        StatusBarUtil.StatusBarLightMode(this);
        CustomUtils.setImmersiveStatusBar(mContext, mIncludeRlView);

        //获取选择宝宝界面传过来的值 0男 1女
        mGender = getIntent().getStringExtra("sex");
        mResource = getIntent().getIntExtra(ACT_SelectBaby.KEY_RESOURCE_TYPE, -1);

        switch (mGender) {
            case "0":
                babyIvHeadPhoto.setImageResource(R.mipmap.addbaby_img_boy);
                break;
            case "1":
                babyIvHeadPhoto.setImageResource(R.mipmap.addbaby_img_girl);
                break;
            default:
                babyIvHeadPhoto.setImageResource((R.drawable.healthdata_icon_headportrait_default));
                break;
        }

        mSp = new AppSharedPreferences(mContext);
        mToken = mSp.getString(Constants.USER_TOKEN);
        mUserId = mSp.getString(Constants.USER_ID);

        //裁剪图片后的保存地址
        imageCropUri = getUri();

        //初始化view
        initView();
    }

    private void initView() {
        //设置title
        includeTvTitle.setText("设置宝宝信息");
        //设置保存按钮
        includeTvRight.setText("保存");
        MoneyFormatUtil.formatMoney(babyEditHeight, null);
        MoneyFormatUtil.formatMoney(babyEditWeight, null);
        // 初始化宝宝关系弹窗
        initSelectRelativeDialog();

        if (entity == null) {
            //根据传过来的男女值设置
            if ("0".equals(mGender)) {
                babyIvSex.setImageResource(R.mipmap.ic_baby_boy);
                babyTvSex.setText("男");
            } else if ("1".equals(mGender)) {
                babyIvSex.setImageResource(R.mipmap.ic_baby_girl);
                babyTvSex.setText("女");
            }
        } else {
            //头像
            imgUri = entity.getImageUrl();
            babyId = entity.getBabyId();
            Glide.with(mContext)
                    .load(entity.getImageUrl())
                    .error(R.drawable.healthdata_icon_headportrait_default)
                    .into(babyIvHeadPhoto);
            //昵称
            babyEditName.setText(entity.getName());
            mGender = entity.getGender();
            //性别 0男  1女
            if ("0".equals(entity.getGender())) {
                babyIvSex.setImageResource(R.mipmap.ic_baby_boy);
                babyTvSex.setText("男");
            } else if ("1".equals(entity.getGender())) {
                babyIvSex.setImageResource(R.mipmap.ic_baby_girl);
                babyTvSex.setText("女");
            }
            //生日
            babyTvBirthday.setText(entity.getBirthDay());
            //身高
            babyEditHeight.setText(entity.getHeight());
            //体重
            babyEditWeight.setText(entity.getWeight());
            //关系名
            tvRelation.setText(entity.getRelationshipName());
            //此处修复了健康页跳转到编辑信息页没有携带id name 的问题
            selectedRelationId = entity.getRelationshipId();
            selectedRelationName = entity.getRelationshipName();
        }


        //设置日期格式
        setBabyBirthday(babyTvBirthday);
    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean isBindEventBusHere() {
        return false;
    }

    @Override
    protected boolean toggleOverridePendingTransition() {
        return false;
    }

    @Override
    protected TransitionMode getOverridePendingTransitionMode() {
        return null;
    }

    @Override
    protected boolean isApplyKitKatTranslucency() {
        return false;
    }

    @Override
    public void showBusinessError(ErrorBean error) {

    }

    @Override
    public void showError(String msg) {
        ToastUtil.makeText(mContext, msg, false);
    }

    public void setBabyBirthday(final TextView textView) {
        customDatePicker = new CustomDatePicker(this, new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time) { // 回调接口，获得选中的时间
                textView.setText(time.split(" ")[0]);
            }
        }, "2012-01-01 00:00",
                AppDateUtil.getTimeStamp(System.currentTimeMillis(), AppDateUtil.YYYY_MM_DD_HH_MM)); //
        // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
        customDatePicker.showSpecificTime(false); // 显示时和分
        customDatePicker.setIsLoop(false); // 允许循环滚动
    }

    @OnClick({R.id.include_iv_back, R.id.baby_iv_head_photo, R.id.baby_tv_birthday,
            R.id.include_tv_right, R.id.tv_select_relation})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.include_iv_back://返回键
                finish();
                break;
            case R.id.baby_iv_head_photo://上传头像
                requestPhotosPermissions();
                break;
            case R.id.baby_tv_birthday://选择宝宝生日
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
                String now = sdf.format(new Date());
                customDatePicker.show(now);
                break;
            case R.id.include_tv_right://保存按钮
                postBaby();
                break;
            case R.id.tv_select_relation:// 选择宝宝关系
                mPresenter.getRelationList();
                break;
        }
    }

    @Override
    public void addBabySucceed() {
        //添加或修改成功
//        readyGo(ACT_BabyManage.class);

        switch (mResource) {
            case START_FROM_HEALTH:
                readyGo(ACT_HomePage.class);
                break;
            case START_FROM_RELATION:
                readyGo(ACT_Family.class);
                break;
            case START_FROM_SWITCH:
                readyGo(ACT_SwitchBaby.class);
                break;

        }

    }

    @Override
    public void getImgUri(UpLoadFileEntity entity) {
        if (entity == null) {
            return;
        }
        imgUri = entity.getShowImg();
        Glide.with(mContext)
                .load(imgUri)
                .into(babyIvHeadPhoto);
    }

    @Override
    public void updateRelationList(List<RelationEntity.ListBean> list) {
        mRelationAdapter.update(list, true);
        mRelativeDialog.show();
    }

    public void postBaby() {

        if (StringUtil.isEmpty(imgUri)) {
            ToastUtil.makeText(mContext, "请上传宝宝头像", false);
            return;
        }

        //宝宝昵称
        String babyName = babyEditName.getText().toString().trim();
        if (StringUtil.isEmpty(babyName)) {
            ToastUtil.makeText(mContext, "请输入宝宝昵称", false);
            return;
        }
        //宝宝生日
        String babyBirthday = babyTvBirthday.getText().toString().trim();
        if (StringUtil.isEmpty(babyBirthday)) {
            ToastUtil.makeText(mContext, "请选择宝宝生日", false);
            return;
        }

        //宝宝生日
        String relation = tvRelation.getText().toString().trim();
        if (StringUtil.isEmpty(relation)) {
            ToastUtil.makeText(mContext, "请选择与宝宝关系", false);
            return;
        }

        //宝宝身高
        String babyHeight = babyEditHeight.getText().toString().trim();
        if (StringUtil.isEmpty(babyHeight)) {
            ToastUtil.makeText(mContext, "请输入宝宝身高", false);
            return;
        }
        //宝宝体重
        String babyWeight = babyEditWeight.getText().toString().trim();
        if (StringUtil.isEmpty(babyWeight)) {
            ToastUtil.makeText(mContext, "请输入宝宝体重", false);
            return;
        }

        //保存宝宝信息
        mPresenter.postBabyInfo(Constants.TOKEN, babyName,
                babyBirthday, babyHeight, babyWeight, imgUri,
                babyId, mGender, selectedRelationId, selectedRelationName);

    }

    /**
     * 打开相机和相册的弹出框
     */
    public void OpenCameraDialog() {
        mOpenCamersDialog = new AlertDialog.Builder(mContext)
                .setContentView(R.layout.dialog_open_camera)
                .fromBottom(true)
                .fullWidth()
                .setOnClickListener(R.id.tv_photo_album, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        choosePhoto();
                    }
                })
                .setOnClickListener(R.id.tv_take_photos, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        takePhoto();
                    }
                })
                .setOnClickListener(R.id.tv_cancel_camera, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mOpenCamersDialog.dismiss();
                    }
                })
                .show();
    }

    /**
     * 点击拍照,动态申请权限
     */
    public void requestPhotosPermissions() {
        //第二个参数是需要申请的权限
        if (ContextCompat.checkSelfPermission(mContext,
                Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            // 进入这儿表示没有权限
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
                // 提示已经禁止
                ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, CAMERA_REQUEST_CODE);
            } else {
                //权限还没有授予，需要在这里写申请权限的代码
                // 第二个参数是一个字符串数组，里面是你需要申请的权限 可以设置申请多个权限
                // 最后一个参数是标志你这次申请的权限，该常量在onRequestPermissionsResult中使用到
                ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, CAMERA_REQUEST_CODE);
            }

        } else { //权限已经被授予，在这里直接写要执行的相应方法即可
            OpenCameraDialog();
        }
    }

    /**
     * 跳转系统的App应用详情页
     */
    protected void toAppDetailSetting() {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
        localIntent.setData(Uri.fromParts("package", getPackageName(), null));
        startActivity(localIntent);
    }

    /**
     * 拍照实现方法
     */
    private void takePhoto() {
        //打开相机后，关闭弹出框
        mOpenCamersDialog.dismiss();

        // 跳转到系统的拍照界面
        Intent intentToTakePhoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 指定照片存储位置为sd卡本目录下
        // 这里设置为固定名字 这样就只会只有一张temp图 如果要所有中间图片都保存可以通过时间或者加其他东西设置图片的名称
        // File.separator为系统自带的分隔符 是一个固定的常量
        mTempPhotoPath = Environment.getExternalStorageDirectory() + File.separator + "photo.jpeg";
        // 获取图片所在位置的Uri路径    *****这里为什么这么做参考问题2*****
        /*imageUri = Uri.fromFile(new File(mTempPhotoPath));*/
        imageUri = FileProvider.getUriForFile(this, "com.egg.provider",
                new File(mTempPhotoPath));
        //下面这句指定调用相机拍照后的照片存储的路径
        intentToTakePhoto.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intentToTakePhoto, CAMERA_REQUEST_CODE);
    }

    /**
     * 打开相册方法实现
     */
    private void choosePhoto() {
        //选择相册后，关闭弹出框
        mOpenCamersDialog.dismiss();

        Intent intentToPickPic = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        // 如果限制上传到服务器的图片类型时可以直接写如："image/jpeg 、 image/png等的类型" 所有类型则写 "image/*"
        intentToPickPic.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intentToPickPic, GALLERY_REQUEST_CODE);
    }

    /**
     * 界面回调方法 用于将得到的照片处理
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {
            case CAMERA_REQUEST_CODE:   //调用相机后返回
                if (resultCode == RESULT_OK) {
                    cropPhoto(imageUri);       //裁剪
                }
                break;
            case GALLERY_REQUEST_CODE:    //调用相册后返回
                if (resultCode == RESULT_OK) {
                    Uri uri = data.getData();
                    cropPhoto(uri);       //裁剪
                }
                break;
            case GO_TO_ZOOM:     //调用剪裁后返回
                if (resultCode == RESULT_OK) {
                    String encodedPath = imageCropUri.getEncodedPath();
                    Uri uriFromFilePath = UriUtils.getUriFromFilePath(encodedPath);
                    upLoad(uriFromFilePath);
                }
                break;
        }

    }

    //把图片上传到服务器
    public void upLoad(Uri uri) {
        Bitmap bitmap = UriUtils.decodeUriAsBitmap(this, uri);
        String photo = saveImage("photo", bitmap);
        mPresenter.upImg(photo);
    }

    /**
     * 权限申请回调方法
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == CAMERA_REQUEST_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                OpenCameraDialog();
            } else {
                // Permission Denied
            }
        }
    }


    /**
     * 裁剪图片
     */
    private void cropPhoto(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");

        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("return-data", true);
        intent.putExtra("noFaceDetection", true);
        //裁剪之后，保存在裁剪文件中，关键
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageCropUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        startActivityForResult(intent, GO_TO_ZOOM);
    }

    /**
     * 得到存储图片bitmap的路径
     *
     * @param name
     * @param bmp
     * @return
     */
    public String saveImage(String name, Bitmap bmp) {
        File appDir = new File(Environment.getExternalStorageDirectory().getPath());
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = name + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            fos.close();
            return file.getAbsolutePath();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private Uri getUri() {
        File tmpDir = new File(Environment.getExternalStorageDirectory() + "/image/");
        if (!tmpDir.exists()) {
            tmpDir.mkdirs();
        }
        File img = new File(tmpDir.getAbsolutePath() + "/pic.jpeg");
        if (img.exists()) {
            img.delete();
        }
        return Uri.fromFile(img);
    }

    private void initSelectRelativeDialog() {

        mRelativeDialog = new AlertDialog.Builder(mContext)
                .setContentView(R.layout.dialog_simple_list)
                .setWidthAndHeight(mScreenWidth - DisplayUtil.dip2px(mContext, 20), ViewGroup.LayoutParams.WRAP_CONTENT)
                .setCancelableOntheOutside(true)
                .fromBottom(true)
                .create();
        RecyclerView rvBabyList = mRelativeDialog.findViewById(R.id.rv_list);
        rvBabyList.setLayoutManager(new GridLayoutManager(mContext, 3));
        mRelationAdapter = new ADA_BabyRelation(mContext);
        rvBabyList.setAdapter(mRelationAdapter);

        mRelativeDialog.setOnClickListener(R.id.tv_cancel, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mRelativeDialog.dismiss();
            }
        });

        mRelationAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {

                RelationEntity.ListBean listBean = mRelationAdapter.getDatas().get(position);
                selectedRelationId = listBean.getLabel();
                selectedRelationName = listBean.getValue();
                tvRelation.setText(selectedRelationName);
                mRelativeDialog.dismiss();

            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
    }

}
